var table;

$(function () {
    loadDealerList();
});

function loadDealerList() {
    var url = baseDealerUrl + "query/dealer";
    ajaxCommon.request('get',url,{},function(data){
        loadTable(data.data);
    })
}

function loadTable(data) {
    $("#dealerList").DataTable({
        data: data,
        searching: true,
        ordering: false,
        bLengthChange: false,
        select: true,
        columns: [
            {data: 'dealerName'},
            {
                data: function (data, type, row, meta) {
                    if (isNull(data.director) && isNull(data.phone)) {
                        return "";
                    } else if (isNull(data.phone)) {
                        return data.director;
                    } else if (isNull(data.director)) {
                        return data.phone;
                    } else {
                        return data.director + "(" + data.phone + ")";
                    }
                }
            },
            {data: 'regionName'},
            {
                data: 'created',
                render: function (data, type, row, meta) {
                    return formatDate1(row.created);
                }
            },
            {data: 'num'}
        ],
        pagingType: "full_numbers",
        language: {
            "sProcessing": "处理中...",
            "sLengthMenu": "显示 _MENU_ 项结果",
            "sZeroRecords": "没有匹配结果",
            "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
            "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
            "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
            "sInfoPostFix": "",
            "sSearch": "搜索:",
            "sUrl": "",
            "sEmptyTable": "表中数据为空",
            "sLoadingRecords": "载入中...",
            "sInfoThousands": ",",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页"
            },
            oAria: {
                "sSortAscending": ": 以升序排列此列",
                "sSortDescending": ": 以降序排列此列"
            }
        },
        columnDefs: [{
            targets: 5,
            render: function (data, type, row, meta) {
                return "<button type='button' style='margin-right: 10px;border: 1px solid #0D1113;color: #0D1113;background: transparent;' class='btn btn-primary' onclick='editDealer(" + JSON.stringify(row) + ");'>编辑</button>";
            }
        }]
    });
}

/**
 * 编辑4S店的事件
 * @param dealer
 */
function editDealer(dealer) {
    loadData(dealer, "update");
}

/**
 * 加载地区数据
 * @param dealer
 * @param type
 */
function loadData(dealer, type) {
    $("#type").text(type);
    if (type === "update") {
        $(".modal-title").text("编辑");
    } else {
        $(".modal-title").text("新增");
    }
    var url = baseRegionUrl + "list/region";
    ajaxCommon.request('get',url,{},function (data) {
        var arr = [];
        $(data.data.rows).each(function (index, obj) {
            if (obj.id !== 0) {
                var region = {"id": obj.id, "text": obj.name};
                arr.push(region);
            }
        });
        $('#region').select2({
            data: arr,
            minimumResultsForSearch: Infinity
        });
        if (dealer) {
            $("#id").text(dealer.dealerCode);
            initForm(dealer);
        }
        if (type === "update") {
            $("#dealerCode").attr("disabled", true);
        } else {
            $("#dealerCode").attr("disabled", false);
        }
        $('#editModal').modal('show');

    })
}

/**
 * 对编辑4S店的表单进行初始化
 * @param dealer
 */
function initForm(dealer) {
    $("#dealerCode").val(dealer.dealerCode);
    $("#dealerName").val(dealer.dealerName);
    $("#director").val(dealer.director);
    $("#directorPhone").val(dealer.phone);
}

/**
 * 提交编辑4S店的事件
 */
function submitEdit() {
    var url = baseDealerUrl + $("#type").text() + "/dealer";
    var dealerCode = $("#dealerCode").val();
    var dealerName = $("#dealerName").val();
    var regionId = $("#region").val();
    var director = $("#director").val();
    var directorPhone = $("#directorPhone").val();
    var re_s = new RegExp("\s");
    if (isNull(dealerCode)) {
        swal("经销商代码不能为空");
        return;
    }
    if (isNull(dealerName)) {
        swal("经销商名称不能为空");
        return;
    }
    if (isNull(director)) {
        swal("负责人名称不能为空");
        return;
    }
    if (isNull(directorPhone)) {
        swal("负责人手机不能为空");
        return;
    }
    if (dealerCode.match(re_s)) {
        swal("经销商代码格式不正确");
        return;
    }
    if (dealerName.match(re_s)) {
        swal("经销商名称格式不正确");
        return;
    }
    if (director.match(re_s)) {
        swal("负责人名称格式不正确");
        return;
    }
    if (directorPhone.match(re_s)) {
        swal("负责人手机格式不正确");
        return;
    }
    var re = new RegExp("0?(13|14|15|17|18)[0-9]{9}");
    var match = directorPhone.match(re);
    if (isNull(match) || match.length <= 0 || directorPhone.length !== 11) {
        swal("手机号不合法");
        return;
    }
    var data = {
        "dealerCode": dealerCode,
        "dealerName": dealerName,
        "regionId": regionId,
        "director": director,
        "directorPhone": directorPhone
    };
    ajaxCommon.request('post',url,JSON.stringify(data),function (data) {
        $("#dealerList").remove();
        var tableHtml = '<table id="dealerList" class="table table-striped table-hover" cellspacing="0" width="100%"><thead><tr><th>4S店名称</th><th>负责人</th><th>所属区域</th><th>建立时间</th><th>设备数量</th><th>操作</th></tr></thead></table>';
        $(".box-body").html(tableHtml);
        loadDealerList();
        $('#editModal').modal('hide');
    })
}

/**
 * 新增4S店事件
 */
function addDealer() {
    emptyForm($("#form"));
    loadData(null, "add");
}
